<script>
import axios from "axios";

export default {
    name: "XiaoQuComponent",
    data(){
        return{
            value1: '',
            input: '',
            dialogFormVisible: false,
            dialogTitle:'',//对话框标题
            form: {
                location:'', //经纬度
                "communityId": "",
                "communityName": "",
                "communityAddress": "",
                "createTime": "",
                "communityProvince": "",
                "communityCity": "天",
                "communityDistrict": "",
                "communityAreaCode": 0,
                "communityLatitude": "",
                "communityLongitude": "",
                "communityStatus": 1,
                "communityCoordinates": "",
                "distance": "",
                "communityUserCount": 0,
                "communityShopCount": 0,
                "addOrUpdateFlag": "",
            },
            tableData:[],
            tableData2:[],
            addressAll:[],   //省市区
            address: [], //你选择的地址
            formLabelWidth: '120px',
            //查看关联门店里的搜索数据
            association: false,
            checkBtn2: {
                villageName2: "",
                pageNum: 1,
                pageSize: 10,
            },
            addAssociation: false,
            checkBtn3: {
                villageName3: "",
            },
            //搜索框数据对象
            searchContent:{
                name: "",
                time:[],
                pageNum: 1,
                pageSize: 10,
                communityName:"",
            },
            row:{},      // 全局row 把scope.row赋给它
            allId:-1,   //全局id用来在新增和修改是做判断
            page:{
                pageSize:10,    //默认每页显示10条
                currentPage:1,  //默认显示第一页
                total:0 //总条数
            },
        }
    },
    //   页面初始化后执行
    created() {
        //this.getAllProvinceAndCityList();
        // this.getAllXiaoqu();
        this.flushPage();
    },
    methods:{
        //获取省市
        getAllProvinceAndCityList() {
            // 获取全国所有省份和城市的列表
            var that = this;
            this.$http
                .get("https://restapi.amap.com/v3/config/district", {
                    // 高德地图的API
                    params: {
                        key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
                        keywords: "中国",
                        subdistrict: 3,
                        extensions: "base",
                    },
                })
                .then((response) => {
                    console.log(response.data)
                    for(let i = 0;i<response.data.districts[0].districts.length;i++){
                        let provinceMap = new Map();
                        provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
                        provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
                        provinceMap.children = [];
                        that.addressAll.push(provinceMap);  //添加省份
                        for(let j = 0;j < response.data.districts[0].districts[i].districts.length;j++){
                            let cityMap = new Map()
                            cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                            cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                            cityMap.children = [];
                            provinceMap.children.push(cityMap); //添加市
                            for(let k = 0;k <response.data.districts[0].districts[i].districts[j].districts.length;k++){
                                let areaMap = new Map()
                                areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                                areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                                cityMap.children.push(areaMap);   //添加区县
                            }
                        }
                    }
                });
        },
        //获取经纬度
        latitude(){
            this.$http.get("https://restapi.amap.com/v3/geocode/geo?", {
                    // 高德地图的API
                    params: {
                        key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
                        address: this.address.join(""),
                    },
                }).then((res) => {
                    let rdata = res.data;
                    let geo = rdata.geocodes[0];
                    this.form.location = geo.location;          //经纬度
                    console.log(this.form.location);
                    this.form.communityLongitude = this.form.location.split(',')[0];
                    this.form.communityLatitude = this.form.location.split(',')[1];
            }).catch(()=>{
                this.$message.error('请获取位置');
            });
        },
        save() {
            if(this.allId === -1){   //allId为空 新增
                this.dialogFormVisible = false;
                this.form.communityProvince = this.address[0];
                this.form.communityCity = this.address[1];
                this.form.communityDistrict = this.address[2];
                this.axios.post("/addCommunity", {
                    communityName: this.form.communityName,
                    addOrUpdateFlag: 1,
                    communityProvince: this.form.communityProvince,
                    communityCity: this.form.communityCity,
                    communityDistrict: this.form.communityDistrict,
                    communityAreaCode: "",
                    communityLatitude: this.form.communityLatitude,
                    communityLongitude: this.form.communityLongitude,
                    communityAddress: this.form.communityAddress,
                    communityId: "",
                    communityCoordinates: "",
                }).then((res) => {
                    console.log(res.data);
                    this.clearForm();
                    this.flushPage();
                })
            }else{      //allId不为空 修改
                this.dialogFormVisible = false;
                this.form.communityProvince = this.address[0];
                this.form.communityCity = this.address[1];
                this.form.communityDistrict = this.address[2];
                this.axios.post("/communityUpdate", {
                    communityName: this.form.communityName,
                    addOrUpdateFlag: 2,
                    communityProvince: this.form.communityProvince,
                    communityCity: this.form.communityCity,
                    communityDistrict: this.form.communityDistrict,
                    communityAreaCode: "",
                    communityLatitude: this.form.communityLatitude,
                    communityLongitude: this.form.communityLongitude,
                    communityAddress: this.form.communityAddress,
                    communityId: this.row.communityId,
                    communityCoordinates: "",
                    distance: this.form.distance,
                    communityUserCount: this.form.communityUserCount,
                    communityStatus: this.form.communityStatus,
                }).then((res) => {
                    console.log(res.data);
                    this.clearForm();
                    setTimeout(this.flushPage,500)
                })
            }
        },
        //新增小区
        addXiaoqu(){
            this.dialogTitle = "新增小区";
            this.dialogFormVisible = true;
            this.allId = -1;
        },
        //保存后清空表单
        clearForm(){
            this.form.communityName = "";
            this.form.address = [];
            this.form.communityAddress="";
            this.form.location = "";
        },
        //格式化时间
        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        //取消
        cancel(){
            this.dialogFormVisible = false;
        },
        //编辑小区
        editClick(row){
            this.dialogTitle = "编辑小区";
            this.dialogFormVisible = true;
            this.row = row;
            this.allId = this.row.communityId;
            console.log(this.allId);

            this.form.communityId = this.row.communityId;
            this.form.communityName = this.row.communityName;
            this.form.communityAddress = this.row.communityAddress;
        },
        //获取小区数据
        /*getAllXiaoqu(){
            this.axios.get("community/communityList?",{
                params:{
                    name:"",
                    startTime:"",
                    endTime:"",
                    pageNum:1,
                    pageSize:10,
                    communityName:""
                }
            }).then(res=>{
                console.log(res)
                this.tableData = res.data.data.list;
                console.log(this.tableData);
            })
        },*/
        //刷新页面
        flushPage(){
            this.axios.get("/communityList",
                {
                    params:{
                        //传输的参数
                        name:"",
                        startTime:"",
                        endTime:"",
                        pageNum: 1,
                        pageSize: 10,
                        communityName:"",
                    }
                }).then((res)=>{
                this.tableData=res.data.data.list;
                //页面加载时添加总数量
                this.page.total=res.data.data.total;
            }).catch(err=>{ console.log(err);})
        },
        //删除小区
        deleteClick(index){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.axios.post("/communityDelete",{
                    communityId:index,
                }).then((res) => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.flushPage();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //搜索
        searchClick(){
            this.axios.get( '/communityList',
                {
                    params:{
                        //传输的参数
                        name:this.searchContent.name===undefined?'':this.searchContent.name,
                        communityName:this.searchContent.name===undefined?'':this.searchContent.name,
                        pageNum:this.searchContent.pageNum===undefined?'':this.searchContent.pageNum,
                        pageSize:this.searchContent.pageSize===undefined?'':this.searchContent.pageSize,
                        startTime:this.searchContent.time[0]===undefined?'':this.formatDateTime(this.searchContent.time[0]),
                        endTime:this.searchContent.time[1]===undefined?'':this.formatDateTime(this.searchContent.time[1]),
                    }
                }
            ).then((res)=>{
                //处理响应数据
                console.log(res);
                //真正需要的数据
                console.log(res.data.data.list);
                //将得到的数据加载到tableData
                this.tableData=res.data.data.list;
            }).catch(err=>{})
        },
        //分页函数
        //点击按钮切换页面
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage; //每次点击分页按钮，当前页发生变化
            console.log("页码切换：" +  this.page.currentPage);          // 获取改变页码后的数据
            this.axios.get('/communityList',
                {
                    params:{
                        //传输的参数
                        courierStationName:"",
                        communityName:"",
                        courierStationStatus:"",
                        pageNum: this.page.currentPage,
                        pageSize: this.page.pageSize,
                        startTime:'',
                        endTime:'',
                    }
                }
            ).then((res)=>{
                //更新表格数据
                this.tableData=res.data.data.list;
                console.log(this.tableData)
                //设置total
                this.page.total=res.data.data.total
                console.log(this.page.total)
            }).catch(err=>{
                console.log(err)
            });
        },
        //查看关联门店
        relativeShop(){
            this.association=true;
            this.axios.get(
                "/communityShop",{
                    params:{
                        page:1,
                        size:10,
                    }
                }).then((res) => {
                //res存储的说就是通过链接取得的数据；
                console.log(res.data.list)
                this.tableData2 = res.data.list
                // console.log("-------" + this.tableData2)
            }).catch((err) => {
                console.log("如果请求失败，才会执行catch");
            });
        },
        //查看关联门店--->搜索按钮
        lookAssociation() {
            this.axios
                .get("/associationSearch", {
                    params: {
                        pageNum: 1,
                        pageSize: 10,
                        shopName: this.checkBtn2.villageName2,
                    },
                })
                .then((res) => {
                    //res存储的说就是通过链接取得的数据；
                    this.tableData2 = res.data.list;
                    console.log(this.tableData2)
                })
                .catch((err) => {
                    console.log("如果请求失败，才会执行catch");
                });
        },
    }
}
</script>

<template>
    <div class="xiaoqu">
        <div class="xiaoqu-content">
            <div class="searchBox">
                <div class="searchLi">
                    <span class="xiaoquName">小区名称：</span>
                    <input type="text" autocomplete="off" v-model="searchContent.name">
                </div>
                <div class="searchLi">
                    <span>创建时间：</span>
                    <el-date-picker
                        v-model="searchContent.time"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </div>
                <div class="searchBtn">
                    <el-button type="primary" @click="searchClick">搜索</el-button>
                </div>
            </div>
            <div class="addXiaoquBtn">
                <el-button type="text" @click="addXiaoqu" class="addBtn">新增小区</el-button>
                <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
                    <el-form :model="form">
                        <el-form-item label="门店名称" :label-width="formLabelWidth">
                            <el-input v-model="form.communityName" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="所属地区" :label-width="formLabelWidth">
                            <el-cascader
                                :options="addressAll"
                                clearable
                                v-model="address"
                                :props="{value:'label'}"
                            ></el-cascader>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth">
                            <el-input v-model="form.communityAddress" autocomplete="off" placeholder="请填写详细地址"></el-input>
                        </el-form-item>
                        <el-form-item label="门店坐标" :label-width="formLabelWidth">
                            <el-button :plain="true" v-model="form.location" @click="latitude">获取位置</el-button>
                            <span>{{form.location}}</span>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取 消</el-button>
                        <el-button @click="save">保 存</el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="xiaoqu-table">
                <el-table
                    :data="tableData"
                    border
                    :cell-style="{'text-align':'center'}"
                    :header-cell-style="{background: '#1890ff',color: '#ffffff','text-align': 'center'}">
                    <el-table-column
                        prop="communityId"
                        label="Id">
                    </el-table-column>
                    <el-table-column
                        prop="communityName"
                        label="名称">
                    </el-table-column>
                    <el-table-column
                        prop="communityAddress"
                        label="位置">
                    </el-table-column>
                    <el-table-column
                        prop="communityUserCount"
                        label="用户数量">
                    </el-table-column>
                    <el-table-column
                        prop="communityShopCount"
                        label="关联门店">
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间">
                    </el-table-column>
                    <el-table-column
                        label="操作">
                        <template slot-scope="scope">
                            <el-button @click="relativeShop" type="text" size="small">查看关联门店</el-button>
                            <!--   弹窗内容-->
                            <el-dialog
                                title="查看关联门店"
                                :visible.sync="association"
                                :close-on-click-modal="false"
                            >
                                <el-form :model="checkBtn2">
                                    <el-form-item>
                                        <el-input
                                            v-model="checkBtn2.villageName2"
                                            autocomplete="off"
                                            :style="{
                                            width: '200px',
                                            marginRight: '20px',
                                            float: 'left',
                                          }"></el-input>
                                        <el-form-item style="margin-left: 10px; float: left">
                                            <el-button type="primary" @click="lookAssociation">搜索</el-button>
                                            <el-button type="primary" @click="addAssociation = true">添加关联门店</el-button>
                                            <!--  addAssociation = true  -->
                                            <el-dialog
                                                title="添加关联门店"
                                                :visible.sync="addAssociation"
                                                append-to-body>
                                                <el-form :model="checkBtn3">
                                                    <el-form-item>
                                                        <el-input
                                                            v-model="checkBtn3.villageName3"
                                                            autocomplete="off"
                                                            :style="{
                                                            width: '200px',
                                                            marginRight: '20px',
                                                            float: 'left',
                                                          }"></el-input>
                                                        <el-form-item
                                                            style="margin-left: 10px; float: left">
                                                            <el-button type="primary" @click="lookAssociation"
                                                            >搜索</el-button>
                                                        </el-form-item>
                                                        <el-form-item>
                                                            <el-table
                                                                :data="tableData2"
                                                                border
                                                                style="width: 100%"
                                                                :header-cell-style="{
                                                              backgroundColor: '#1890FF',
                                                              color: '#FFFFFF',
                                                              textAlign: 'center',
                                                            }">
                                                                <el-table-column
                                                                    prop="panghuShopId"
                                                                    label="序号"
                                                                    width="50"
                                                                ></el-table-column>
                                                                <el-table-column
                                                                    prop="shopName"
                                                                    label="名称"
                                                                ></el-table-column>
                                                                <el-table-column
                                                                    prop="panghuShopId"
                                                                    label="ID"
                                                                ></el-table-column>
                                                                <el-table-column prop="shopSort" label="排序"></el-table-column>
                                                                <el-table-column
                                                                    prop="shopAddress"
                                                                    label="地址"
                                                                ></el-table-column>
                                                                <el-table-column
                                                                    prop="salesVolume"
                                                                    label="订单数量"
                                                                ></el-table-column>
                                                            </el-table>
                                                        </el-form-item>
                                                    </el-form-item>
                                                </el-form>
                                                <div slot="footer" class="dialog-footer">
                                                    <el-button @click="addAssociation = false">取 消</el-button>
                                                    <el-button type="primary" @click="addAssociation = false">确 定</el-button>
                                                </div>
                                            </el-dialog>
                                        </el-form-item>
                                    </el-form-item>
                                    <el-table
                                        :data="tableData2"
                                        border
                                        style="width: 100%"
                                        :header-cell-style="{
                                          backgroundColor: '#1890FF',
                                          color: '#FFFFFF',
                                          textAlign: 'center',
                                        }">
                                        <el-table-column
                                            prop="panghuShopId"
                                            label="序号"
                                            width="50"
                                        ></el-table-column>
                                        <el-table-column
                                            prop="shopName"
                                            label="名称"
                                        ></el-table-column>
                                        <el-table-column
                                            prop="panghuShopId"
                                            label="ID"
                                        ></el-table-column>
                                        <el-table-column prop="shopSort" label="排序"></el-table-column>
                                        <el-table-column
                                            prop="shopAddress"
                                            label="地址"
                                        ></el-table-column>
                                        <el-table-column
                                            prop="salesVolume"
                                            label="订单数量"
                                        ></el-table-column>
                                        <el-table-column label="操作" width="100"></el-table-column>
                                    </el-table>
                                </el-form>
                                <!-- 分页-->

                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="association = false">取 消</el-button>
                                </div>
                            </el-dialog>

                            <el-button @click="editClick(scope.row)" type="text" size="small">编辑小区</el-button>
                            <el-button @click="deleteClick(scope.row.communityId)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!--分页按钮-->
            <div class="block">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page.sync="page.pageNum"
                    :page-size="10"
                    layout="prev, pager, next,jumper, ->, total"
                    :total="page.total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<style scoped>
.xiaoqu{
    height: 800px;
    background-color: hotpink;
}
.xiaoqu-content{
    padding: 20px;
}
.searchBox{
    display: flex;
    justify-content: flex-start;
}
.searchLi{
    margin-right: 20px;
}
.addXiaoquBtn{
    margin-top: 20px;
}
input{
    height: 34px;
    outline: none;
    border: 1px solid #aaa;
    padding: 0 15px;
    border-radius: 5px;
}
input:hover{
    border: 1px solid #555555;
}
input:focus{
    border: 1px solid #409eff;
}
.addBtn{
    padding: 10px 20px;
    background-color: #409eff;
    color: whitesmoke;
    border: 1px solid #409eff;
}
.xiaoqu-table{
    margin-top: 20px;
    table-layout: auto;
}
</style>